<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class CaptchaController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    //取验证码
    public function captcha(Request $request)
    {
        //返回值包括一个base_64加密的图片和一个key
        $result = app('captcha')->create();

        //缓存验证码
        $key = sprintf("code_%s", $result['key']);
        Cache::put($key,$result['key'], 3600);
        
        echo "<img src='".$result['img']."'><span>{$result['key']}";

        return $this->success($result);

    }

    //验证
    public function verify(Request $request)
    {
        $captcha = $request->input('captcha');
        $captcha = strtolower($captcha);
        $key = Cache::get(sprintf("code_%s", $request->input('key')));

        if(app('captcha')->check($captcha,$key) === false){
            return $this->error('验证码错误');
        }

        return $this->success();
    }
}
